package com.kexilo.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.utils.ServletUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.security.service.TokenService;
import com.kexilo.core.security.domain.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author Kexilo
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    
    private static final Logger log = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);
    
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            log.info("用户 {} 退出成功", userName);
        }
        ServletUtils.renderString(response, new ObjectMapper().writeValueAsString(R.ok("退出成功")));
    }
}
